package cn.jinbyte.web.utils;


import cn.jinbyte.core.exception.BussException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 下载工具
 *
 * @author jinty
 * @since 1.0.0
 */
@Slf4j
@SuppressWarnings("unused")
public class DownloadUtils {

    public static void setHeaderByFilename(String filename, HttpServletResponse response) {
        MediaType mediaType = MediaTypeFactory.getMediaType(filename).orElse(MediaType.APPLICATION_OCTET_STREAM);
        response.setContentType(mediaType.toString());
        String downloadFilename = URLEncoder.encode(filename, StandardCharsets.ISO_8859_1);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + downloadFilename);
    }

    public static void downloadFile(String location, String filename, HttpServletResponse response) {
        downloadFile(new File(location), filename, response);
    }

    public static void downloadFile(File file, String distFilename, HttpServletResponse response) {
        if (!file.exists() || !file.isFile()) {
            throw new BussException("文件下载出错：文件不存在");
        }
        if (StringUtils.isBlank(distFilename)) {
            distFilename = file.getName();
        }
        byte[] buffer = new byte[4096];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            DownloadUtils.setHeaderByFilename(distFilename, response);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BussException("文件下载出错：未知错误");
        }
    }

}
